/* **********************************************************************************/
/* PROCEDURE NAME           : xxapmatchingbycsv_e.p                                 */
/* COPYRIGHT CCWin-In ALL RIGHTS RESERVED. THIS IS AN UNPUBLISHED WORK.             */
/* V8:ConvertMode=Report                                                            */
/* V8:WebEnabled=Yes                                                                */
/* V8:RunMode=Character,Windows                                                     */
/* **********************************************************************************/
/* PROCEDURE TYPE            : API Import                                           */
/* DESCRIPTION               : Supplier invoice import By CSV                       */
/* INCLUDE FILES             :                                                      */
/* CALLED BY                 :                                                      */
/* CALLED PROCEDURES         :                                                      */
/* USER DEFINED FUNCTIONS    :                                                      */
/* **********************************************************************************/
/************************************************************************************/
/*Action  Developer    ECO#  SRR Nbr      ITSM Nbr       PCA Nbr    Date            */
/*------  ------------ ----- ------------ ---------      ---------  ---------       */
/*SRR:              SR:                                                             */
/************************************************************************************/
/*ADNT-NBR:  DATE:05/11/19 ECO: MODIFIED BY:GAO YAN                                 */
/************************************************************************************/

{us/mf/mfdtitle.i}
{us/bbi/gplabel.i}
{us/wb/wbrp01.i}
{us/gl/glsec.i}

{xxjson.i}


{proxy/bcinvoiceapmatchingdef.i}


&GLOBAL-DEFINE TimeStamp1 STRING(Year(today),"9999") + STRING(month(today),"99") + STRING(day(today),"99") + substring(string(time,"hh:mm:ss"),1,2) + substring(string(time,"hh:mm:ss"),4,2) + substring(string(time,"hh:mm:ss"),7,2)

define variable v_prefix      as character        format "x(20)"     no-undo.
define variable v_extn        as character                           no-undo.
define variable v_outpath     as character        format "x(50)"     no-undo.
define variable v_inpath      as character        format "x(50)"     no-undo.
define variable v_sftpip      as character        format "x(20)"     no-undo.
define variable v_sftpid      as character        format "x(20)"     no-undo.
define variable v_sftppw      as character        format "x(15)"     no-undo.
define variable v_infile      as character        format "X(40)"     no-undo.
define variable v_infile1     as character        format "X(40)"     no-undo.
define variable v_file1       as character        format "x(20)"     no-undo.
define variable v_file        as character         format "x(50)"     no-undo.
define variable dir-file      as character                           no-undo.
define variable v_logfile     as character        format "x(50)"     no-undo.

define variable m_line1       as character                           no-undo.
define variable v_name        as character                           no-undo.
define variable m_quote       as character        initial '"'        no-undo.
define variable m_space       as character        initial ' '        no-undo.
define variable errline       as character        format "x(80)"     no-undo.
define variable errfile       as character                           no-undo.
define variable errflpt       as character                           no-undo.
define variable stdfile       as character                           no-undo.
define variable outfile       as character                           no-undo.
define variable m_arg1        as character                           no-undo.
define variable v_tmpstr      as character                           no-undo.
define variable v_count       as integer                             no-undo.
define variable v_flcnt       as integer                             no-undo.
define variable m_success     as logical          format "YES/NO"    no-undo.
define variable m_success1    as logical          format "YES/NO"    no-undo.
define variable v_import         as logical       init   "YES"       no-undo.
define variable v_error       as logical                             no-undo.
define variable m_content     as logical          init   "NO"        no-undo.
define variable errflag       as logical                             no-undo.
define variable v_ref         as logical          init   "NO"        no-undo.
define stream   data-stream.
define variable m_entity      like si_entity                         no-undo.
define variable l_fdata       as character                           no-undo.
define variable i             as integer                             no-undo.
define variable m_tmpstr      as character        format "X(150)"    no-undo.
define variable m_voucher     like vo_mstr.vo_ref                    no-undo.
define variable m_status      as logical                             no-undo.
define variable entity_ok     as logical                             no-undo.
define variable m_closed      as logical                             no-undo.
define variable v_trans_qty   as deci                                no-undo.
define variable v_vou_qty     as deci                                no-undo.
define variable v_opn_qty     as deci                                no-undo.
define variable v_batch_run   as LOGI                                no-undo.
define variable v_po_nums     as char             format "X(150)"    no-undo.
define variable m_year        as inte                                no-undo.
define variable v_errmsg      as character        format "x(150)"    no-undo.
define variable v_poamt       as decimal                             no-undo.
define variable v_invamt      as decimal                             no-undo.
define variable inv_cnt as integer    no-undo.
define variable receiver_counter as integer    no-undo.
define variable acc_counter as integer    no-undo.
define variable m_errfile as character  no-undo.
define variable v_cnt     as integer    no-undo.
define variable vc_outputjson                as character format "x(60)" no-undo.
/*For Tax*/
define variable v_taxEnv                     as   character                         no-undo.
define variable v_taxType                    as   character                         no-undo.
define variable v_taxRate                    as   decimal                           no-undo.
define variable v_taxClass                   as   character                         no-undo.
define variable v_taxUsage                   as   character                         no-undo.
define variable v_vatCode                    as   character                         no-undo.
define variable v_taxAccount                 as   character                         no-undo.
define variable v_taxCNAccount               as   character                         no-undo.
define variable v_tzFrom                     as   character                         no-undo.
define variable v_tzTo                       as   character                         no-undo.
define variable v_taxCode                    as   character                         no-undo.
define variable v_taxable                    as   logical                           no-undo.
define variable v_taxExcluded                as  logical                            no-undo.
define variable v_noTax                      as   character        init "NON-TAX"   no-undo.

/* ======== FOR API ========= */
define variable viReturn                     as integer     no-undo.
define variable ilReturnDataset              as logical     no-undo.
define variable ilPartialUpdate              as logical     no-undo.
define variable icPartialUpdateExceptionList as character   no-undo.
define variable ocPrimaryKey                 as character   no-undo.
define variable ocRowid                      as character   no-undo.
define variable oiDraftInstance              as integer     no-undo.
define variable ocPrimaryKeyName             as character   no-undo.
define variable vho                          as handle.
define variable oiReturnStatus               as integer     no-undo.

define variable lvi_row_id                   as integer     no-undo.
define variable v_desc as character no-undo.
define variable v_basedebit as decimal no-undo.
define variable v_cmmt                      as  character format "x(60)" no-undo.

define stream logStrm.
define stream errStrm.

define variable m_apbatch     like apc_batch                no-undo.

define temp-table tt_tAPMatchingCIAPM like tAPMatchingCIAPM .
define temp-table tt_tCInvoiceCIAPM like tCInvoiceCIAPM 
         field tt_seq_number as character
.
define temp-table tt_tAPMatchingCostCIAPM like tAPMatchingCostCIAPM.
define temp-table tt_tAPMatchingCostSafCIAPM like tAPMatchingCostSafCIAPM.

define temp-table tt_CInvoiceAdditional no-undo
   field tt_invoicenumber    as character
   field tt_purchasetype     as character 
   field tt_userid           as character
   field tt_rmk              as character
   field tt_totinvamt        as decimal
   field tt_tottaxamt        as decimal
   field tt_qadinvamt        as decimal
   field tt_qadtaxamt        as decimal
   field tt_taxrate          as decimal
   field tt_currency         as character
   field tt_taxacc       like GL.GLCode
   field tt_glacc        like GL.GLCode
   field tt_division     like division.divisioncode
   field tt_costcenter   like costcentre.costcentrecode
   field tt_allcamt          as decimal
   field tt_oaseq            as character.


/** Get next rc_RowId fuction **/

function fiGetNextRowID returns character:
    lvi_row_id = lvi_row_id - 1.
    return string(string(lvi_row_id) + "row").
end function. 


/** Validation GCM setting for input output directory **/
   {us/xx/xxworkpath_e.i &outbound=YES &inbound=yes &archive=YES}
   m_workpath = m_workpath + "sinv/".
   m_archpath = m_archpath + "sinv/".
   m_outpath = m_outpath + "sinv/".
   m_inpath = m_inpath + "sinv/".
   

      
/** Program form  **/   

form
   
   v_infile                                colon 25  skip
   v_import                                colon 25  skip(2)
   
  
with frame a width 80 side-labels .
setframelabels(frame a:handle).



for first code_mstr no-lock where
   code_domain    = global_domain and
   code_fldname   = "xx_path"
   and code_value = "prefix-scp"
   and code_cmmt <> "":
end.
if not available code_mstr then
do:
   m_arg1 = "SCP_FILE_PREFIX".
   /* GCM is not defined for # */
   {us/bbi/pxmsg.i &msgnum=9610 &errorlevel=4 &msgarg1=m_arg1 &pauseafter=2}
   return .
end. /*NOT AVAILABLE code_mstr*/
else
assign v_prefix = code_cmmt.

for first code_mstr no-lock where
   code_domain  = global_domain and
   code_fldname = "xx_path"
   and code_value   = "extension-scp"
   and code_cmmt   <> "" :
end.
if not available code_mstr then
do:
   m_arg1 = "SCP_FILE_EXTENSION".
   /* GCM is not defined for # */
   {us/bbi/pxmsg.i &msgnum=9610 &errorlevel=4 &msgarg1=m_arg1 &pauseafter=2}
   return .
end. /*NOT AVAILABLE code_mstr*/
else
assign v_extn = code_cmmt.

mainloop:
repeat on error undo mainloop, retry mainloop:
   assign
      v_infile = "" 
      v_import = no
      v_po_nums = "".
   
   clear frame a .
   assign
      v_count  = 0
      v_ref    =  no
      m_year   = year(today)
      m_year   = m_year - int(substring(string(m_year),3,2)).
   
   if c-application-mode <> 'web':u
   then do:
      
      update
      v_infile
      v_import
      with frame a.
   end.
   
   if (c-application-mode = "WEB":U)
   then do:
      {us/wb/wbrp06.i &command = update
      &fields = "v_infile v_import "
      &frm = "a"}
   end.
   
   if  (c-application-mode <> 'web') or  (c-application-mode = 'web' and (c-web-request begins 'data'))
   then do:
      bcdparm = "".
      {us/mf/mfquoter.i v_infile}
      {us/mf/mfquoter.i v_import }
   end.
   

   /*VALIDATE FILE NAME*/
   if v_infile <> " "
   then do:
      if (index(v_infile , ".") <> 0 )
      then do:
         assign v_file1 = "." + v_extn .
         
         if ( substring(v_infile , index(v_infile , ".")) <> v_file1 )
         then do:
            /*INVALID FILE NAME*/
            {us/bbi/pxmsg.i &MSGNUM=184 &ERRORLEVEL=3}
            pause 2 no-message.
            next-prompt v_infile with frame a  .
            undo mainloop,retry mainloop.
         end.
         else if not(v_infile begins v_prefix)
         then do:
            /*INVALID FILE NAME*/
            {us/bbi/pxmsg.i &MSGNUM=184 &ERRORLEVEL=3}
            pause 2 no-message.
            next-prompt v_infile with frame a.
            undo mainloop,retry mainloop.
         end.
         else
         do:
            assign 
               v_name    = substring(v_infile,1,integer(index(v_infile,".")) - 1)
               v_logfile = v_name + ".ftp" .
         end.
      end.  /*IF (INDEX(v_infile , ".") <> 0 )  THEN*/
      else
      do:
         /*INVALID FILE NAME*/
         {us/bbi/pxmsg.i &MSGNUM=184 &ERRORLEVEL=3}
         pause 2 no-message.
         next-prompt v_infile with frame a.
         undo mainloop,retry mainloop.
      end. /*ELSE IF (INDEX(v_infile , ".") <> 0 )  THEN*/
   end.  /* IF v_infile <> " " THEN*/
   else
   do:
      assign 
         v_file = v_prefix + "." + v_extn
         v_logfile = "IV" + {&TimeStamp1} + ".ftp".
      
   end. /*v_infile = ""*/
   
   if search(m_inpath + v_file) <> ?
   then
      unix silent value("chmod 777 " + m_inpath + v_file + " 2>/dev/null").
   
   /*..PROCESSING FILES FROM INPUT DIRECTORY...*/
   v_flcnt = 0.
  /* 
 input stream data-stream from os-dir(m_inpath) no-echo.
 
 repeat:
      
      if v_infile = ""
      then
         assign 
            v_file  = v_prefix + "*." + v_extn
            v_file1 = v_prefix + "*." + v_extn.
      else 
         assign 
            v_file  = v_infile 
            v_file1 = v_infile.
      /** fetch filename from input directory */
      import stream data-stream v_infile1.
      
      if v_infile1 begins "." then next.
      assign
         dir-file = m_inpath + v_infile1 .
      file-info:file-name = dir-file .
      
      if not(file-info:file-type begins "F") then next.
      if ( not(v_infile1 matches v_file ) and not(v_infile1 matches v_file1)) then next .
      
      assign
         v_name = substring(v_infile1,1,integer(index(v_infile1,".")) - 1) + "_" + {&TimeStamp1}.
      
      assign
         errfile     = v_name + ".err"
         stdfile     = v_name + ".std" .
      
      */
      
      
      empty temp-table tt_tAPMatchingCIAPM.
      empty temp-table tt_tCInvoiceCIAPM.
      empty temp-table tt_tAPMatchingCostCIAPM.
      empty temp-table tt_tAPMatchingCostSafCIAPM.
      empty temp-table tt_CInvoiceAdditional.


    
  define variable v_ll as char .
      /*IMPORT Data INPUT FILE*/
      input from value (m_inpath + v_infile)  .
          
      repeat:

  /** File counts **/
         v_flcnt = v_flcnt  + 1.        
         if v_infile begins v_prefix
         then do:        
            empty temp-table api_status.
            import unformatted l_fdata.
        
            if entry(1,l_fdata) = "Head" then do:
                       
               run getTaxDet(input  entry(4,l_fdata),      
                             input  entry(2,l_fdata),
                             input  entry(14,l_fdata), 
                             input  entry(13,l_fdata),
                             input  date(entry(5,l_fdata)),
                             input  yes ,
                             output v_taxEnv,     
                             output v_taxType,
                             output v_taxRate,    
                             output v_vatCode,
                             output v_taxAccount, 
                             output v_tzFrom,
                             output v_tzTo,       
                             output v_taxCode,
                             output v_taxCNAccount).
                  assign
                             v_taxUsage = entry(14,l_fdata)
                             v_taxClass = entry(13,l_fdata).
            
             /*Create tt_tCInvoice Data*/
            Create tt_CInvoiceAdditional.
            assign tt_CInvoiceAdditional.tt_purchasetype = entry(14,l_fdata)
                   tt_CInvoiceAdditional.tt_invoicenumber = entry(3,l_fdata)
                   tt_CInvoiceAdditional.tt_userid = entry(16,l_fdata)
                   tt_CInvoiceAdditional.tt_rmk    = entry(17,l_fdata)
                   tt_CInvoiceAdditional.tt_totinvamt  = dec(entry(11,l_fdata))
                   tt_CInvoiceAdditional.tt_tottaxamt  = dec(entry(12,l_fdata))
                   tt_CInvoiceAdditional.tt_taxrate    = v_taxRate
                   tt_CInvoiceAdditional.tt_taxacc     = entry(18,l_fdata)
                   tt_CInvoiceAdditional.tt_glacc      = entry(19,l_fdata)
                   tt_CInvoiceAdditional.tt_currency   = entry(7,l_fdata)
                   tt_CInvoiceAdditional.tt_costcenter   = entry(9,l_fdata)
                   tt_CInvoiceAdditional.tt_division   = entry(10,l_fdata)
                   tt_CInvoiceAdditional.tt_allcamt    = dec(entry(20,l_fdata))
                   tt_CInvoiceAdditional.tt_oaseq    = entry(21,l_fdata).
                                   
            create tt_tCInvoiceCIAPM .
             assign                   
                  tt_tCInvoiceCIAPM.tcDomainCode               = global_domain
                  tt_tCInvoiceCIAPM.tcCInvoiceReferenceInt     = ""
                  tt_tCInvoiceCIAPM.tcCompanyCode              = entry(2,l_fdata)
                  tt_tCInvoiceCIAPM.tcCInvoiceReference        = entry(3,l_fdata)
                  tt_tCInvoiceCIAPM.tcCreditorCode             = entry(4,l_fdata)
                  tt_tCInvoiceCIAPM.ttCInvoiceDate             = date(entry(5,l_fdata))
                  tt_tCInvoiceCIAPM.ttCInvoicePostingDate      = date(entry(6,l_fdata))
                  tt_tCInvoiceCIAPM.tcCInvoiceCurrencyCode     = entry(7,l_fdata)
                  tt_tCInvoiceCIAPM.tcCInvoiceTSMNumber        = entry(8,l_fdata)
                  tt_tCInvoiceCIAPM.tcCInvoiceCostCentreCode   = entry(9,l_fdata)
                  tt_tCInvoiceCIAPM.tcCInvoiceDivisionCode     = entry(10,l_fdata)
                  tt_tCInvoiceCIAPM.tlIsCreateCInvoice         = yes
                  tt_tCInvoiceCIAPM.tlCInvoiceIsStatusFinal    = yes
                  tt_tCInvoiceCIAPM.tlAPMatchingIsStatusFinal  = yes 
                  /** GY ADD 2-240517 */
                  /*
                  tt_tCInvoiceCIAPM.tlIsCreateCIWithAmountTCIsTax  = yes
                  tt_tCInvoiceCIAPM.tdCInvoiceAmountTC  = dec(entry(11,l_fdata)) +  dec(entry(12,l_fdata)) 
                  tt_tCInvoiceCIAPM.tlCInvoiceIsTaxable  = no 
                  */
                  tt_tCInvoiceCIAPM.tc_Rowid                   = entry(3,l_fdata) /* string(fiGetNextRowID()) */
                  tt_tCInvoiceCIAPM.tt_seq_number              = string(fiGetNextRowID())

                  tt_tCInvoiceCIAPM.tc_Status                  = "N"
                  .
                  /*
                  put unformatted "tcCInvoiceReference:" tt_tCInvoiceCIAPM.tcCInvoiceReference "tt_tCInvoiceCIAPM.tt_seq_number:" tt_tCInvoiceCIAPM.tt_seq_number skip.
                  */   
               if num-entries(l_fdata) < 21
               then do:

                  m_tmpstr = GETTERMLABEL("HEADER",6) + " " + GETTERMLABEL("ENTRIES",7) + " " +
                  lower(GETTERMLABEL("AREA",3)) + " " + lower(GETTERMLABEL("NOT",4)) + " "  +
                  lower(GETTERMLABEL("MATCHING",5)) + " " + lower(GETTERMLABEL("THE",3)) + " " +
                  lower(GETTERMLABEL("REQUIREMENT",11)) + "-" + entry(3,l_fdata).
                                

                  v_cnt = v_cnt + 1.
                  create api_status.
                  assign api_status.data_seq         = v_cnt
                         api_status.traceid          = v_infile1
                         api_status.dataid           = "Header counts"
                         api_status.return_status    = "ERROR"  
                         api_status.message_type     = "Pre-validation"
                         api_status.message_string   =  m_tmpstr.
        
               end. /*NUM-ENTRIES(l_fdata)*/

            end. /* if entry(1,l_fdata) = "Head" */
    
            /*Import Invoice Line Data (PO Receiver)*/
            if entry(1,l_fdata) = "LINE" 
            then do:
            find first prh_hist where prh_domain  = global_domain and prh_receiver = entry(5,l_fdata) no-lock no-error .
            
            
               create tt_tAPMatchingCIAPM.
              assign
                 tt_tAPMatchingCIAPM.tcPurchaseOrderNumber  = prh_hist.prh_nbr /* entry(4,l_fdata) */  /* PO */
                 tt_tAPMatchingCIAPM.tiPurchaseOrderLineNumber = int(entry(6,l_fdata)) /* PO Line */
                 tt_tAPMatchingCIAPM.tcReceiverNumber  = entry(5,l_fdata)  /* Receiver */
                 tt_tAPMatchingCIAPM.tdMatchQty   = decimal(entry(8,l_fdata))  /* Matched Qty */        
                 tt_tAPMatchingCIAPM.tdMatchUnitPrice  = decimal(entry(9,l_fdata))  /* Matched Price */
                 tt_tAPMatchingCIAPM.tcPvoDomain = global_domain.
                 if entry(10,l_fdata) <> "" then 
                assign
                 tt_tAPMatchingCIAPM.tiPvoId  = int(entry(10,l_fdata))  /* PVO_ID */
                 tt_tAPMatchingCIAPM.tiPvodLineId  = int(entry(11,l_fdata))  /* PVOD_LINE */
                 .
                 assign
                 tt_tAPMatchingCIAPM.tlIsRecalculateTaxes  = yes          /* RecalculateTaxes */
                 tt_tAPMatchingCIAPM.ttUsageDate  = ?         /* ttUsageDate */

                 tt_tAPMatchingCIAPM.tlIsPvodFinished  = no  /* Finished */                                     
                 tt_tAPMatchingCIAPM.tc_Rowid   = string(fiGetNextRowID()) /* Unique ID */
                 tt_tAPMatchingCIAPM.tc_ParentRowid   = entry(3,l_fdata) /* Same as Head data */
                 tt_tAPMatchingCIAPM.tc_Status   = "N"
                 .

            
               
               if num-entries(l_fdata) < 9 then
               do:
                  m_tmpstr = GETTERMLABEL("LINE",4) + " " + GETTERMLABEL("ENTRIES",7) + " " +
                  lower(GETTERMLABEL("AREA",3)) + " " + lower(GETTERMLABEL("NOT",4)) + " "  +
                  lower(GETTERMLABEL("MATCHING",5)) + " " + lower(GETTERMLABEL("THE",3)) + " " +
                  lower(GETTERMLABEL("REQUIREMENT",11)) + "-" + entry(3,l_fdata).
                  
                  v_cnt = v_cnt + 1.
                  create api_status.
                  assign api_status.data_seq         = v_cnt
                         api_status.traceid          = v_infile1
                         api_status.dataid           = "Line counts"
                         api_status.return_status    = "ERROR"  
                         api_status.message_type     = "Pre-validation"
                         api_status.message_string   =  m_tmpstr.
                    
               end. /*NUM-ENTRIES(l_fdata) < 11*/
            end. /*iF entry(1,l_fdata) = "Line" Loading Line Data*/
        /* program calculate the addtional cost automatically */
            /*** Import addtional Line data ***/
            if entry(1,l_fdata) = "Additional" 
            then do:             
                   
                   find first domains where domains.domaincode = global_domain no-lock no-error.
      
                   for each domainsharedset of domains no-lock .
                   find SharedSet of domainsharedset  no-lock no-error.
                   if sharedset.sharedsettypecode = "GL" then
                       do:
                         
                          find GL where GL.SharedSet_ID = SharedSet.SharedSet_ID 
                                    and GL.GLcode =  entry(4,l_fdata)
                                    and GL.GLTypeCode = "VAT" no-lock no-error.
                       end.
                   end. /* for each domainsharedset of domains no-lock .  */
                   if not available GL
                   then do:                              
                      create tt_tAPMatchingCostCIAPM.
                      assign
                         tt_tAPMatchingCostCIAPM.tcGLCode = entry(4,l_fdata)
                         tt_tAPMatchingCostCIAPM.tcDivisionCode    = entry(6,l_fdata)
                         tt_tAPMatchingCostCIAPM.tcCostCentreCode  = entry(5,l_fdata)
                         tt_tAPMatchingCostCIAPM.tcProjectCode     = ""
                         tt_tAPMatchingCostCIAPM.tcTaxEnvironment = v_taxEnv
                         tt_tAPMatchingCostCIAPM.tcTaxUsage = v_taxUsage
                         tt_tAPMatchingCostCIAPM.tcTaxClass = v_taxClass
                         tt_tAPMatchingCostCIAPM.tc_Rowid      = string(fiGetNextRowID())
                         tt_tAPMatchingCostCIAPM.tc_ParentRowid = entry(3,l_fdata)
                         tt_tAPMatchingCostCIAPM.tc_Status      = "N"
                      .                                                              
                     assign
                         tt_tAPMatchingCostCIAPM.tdDebitTC  = decimal(entry(7,l_fdata))
                         tt_tAPMatchingCostCIAPM.tdDebitLC  = decimal(entry(7,l_fdata))
                         tt_tAPMatchingCostCIAPM.tdDebitCC  = decimal(entry(7,l_fdata)).
                         
                   end. /* if not available GL*/
                   else do:
                    
                      create tt_tAPMatchingCostCIAPM.
                      assign
                         tt_tAPMatchingCostCIAPM.tcGLCode             = entry(4,l_fdata)
                         tt_tAPMatchingCostCIAPM.tcTaxEnvironment     = v_taxEnv
                         tt_tAPMatchingCostCIAPM.tcTaxUsage           = v_taxUsage
                         tt_tAPMatchingCostCIAPM.tcTaxClass           = v_taxClass
                         tt_tAPMatchingCostCIAPM.ttTaxPointDate       = today
                         tt_tAPMatchingCostCIAPM.tcTaxTransactionType = "55"
                         tt_tAPMatchingCostCIAPM.tcTransactionType    = "Purchase"
                         tt_tAPMatchingCostCIAPM.tc_Rowid             = string(fiGetNextRowID())
                         tt_tAPMatchingCostCIAPM.tc_ParentRowid       = entry(3,l_fdata)
                         tt_tAPMatchingCostCIAPM.tc_Status            = "N"
                         tt_tAPMatchingCostCIAPM.tcPostingVatInOut    = "Input"
                         tt_tAPMatchingCostCIAPM.tcFromTaxZone        = v_tzFrom
                         tt_tAPMatchingCostCIAPM.tcToTaxZone          = v_tzTo
                         tt_tAPMatchingCostCIAPM.tcTaxType            = v_taxType
                         tt_tAPMatchingCostCIAPM.tcPostingVatCode     = v_taxCode
                         tt_tAPMatchingCostCIAPM.tcPostingVatDomain   = global_domain
                         tt_tAPMatchingCostCIAPM.tcCurrencyCode       = tt_CInvoiceAdditional.tt_currency
                         .                                                               
                      assign
                         tt_tAPMatchingCostCIAPM.tdVatDebitTC  = decimal(entry(7,l_fdata))
                         tt_tAPMatchingCostCIAPM.tdVatDebitLC  = decimal(entry(7,l_fdata))
                         tt_tAPMatchingCostCIAPM.tdVatDebitCC  = decimal(entry(7,l_fdata)).
                         
                         v_basedebit = (tAPMatchingCostCIAPM.tdVatDebitLC * 100) / tAPMatchingCostCIAPM.tdVatDebitLC no-error.
                         v_basedebit = round(v_basedebit,2).
                         
                         assign
                            tt_tAPMatchingCostCIAPM.tdBaseDebitTC = v_basedebit
                            tt_tAPMatchingCostCIAPM.tdBaseDebitLC = v_basedebit
                            tt_tAPMatchingCostCIAPM.tdBaseDebitCC = v_basedebit.
                       end. /* else do **/
                  
                            
               if entry(7,l_fdata) = "0" then
               m_tmpstr = gettermlabel("ZERO",4) + " " +
               lower(gettermlabel("AMOUNT",5)) + " " +
               lower(gettermlabel("ENTERED",7)) + " " +
               lower(gettermlabel("IN",2)) + " " +
               lower(gettermlabel("ADDITIONAL_CHARGES",10)) + " " +
               lower(gettermlabel("COST",4)) + " " +
               entry(3,l_fdata).
               
            
               v_cnt = v_cnt + 1.
                  create api_status.
                  assign api_status.data_seq         = v_cnt
                         api_status.traceid          = v_infile1
                         api_status.dataid           = "Amount"
                         api_status.return_status    = "ERROR"  
                         api_status.message_type     = "Pre-validation"
                         api_status.message_string   =  m_tmpstr.

               if num-entries(l_fdata) < 9 then
               do:
                  m_tmpstr = GETTERMLABEL("COST",4) + " " + GETTERMLABEL("ENTRIES",7) + " " +
                  lower(GETTERMLABEL("AREA",3)) + " " + lower(GETTERMLABEL("NOT",4)) + " "  +
                  lower(GETTERMLABEL("MATCHING",5)) + " " + lower(GETTERMLABEL("THE",3)) + " " +
                  lower(GETTERMLABEL("REQUIREMENT",11)) + " " + entry(3,l_fdata).
                  
            

                  v_cnt = v_cnt + 1.
                  create api_status.
                  assign api_status.data_seq         = v_cnt
                         api_status.traceid          = v_infile1
                         api_status.dataid           = "Line counts"
                         api_status.return_status    = "ERROR"  
                         api_status.message_type     = "Pre-validation"
                         api_status.message_string   =  m_tmpstr.

               end. /*NUM-ENTRIES(l_fdata,"^") < 10*/
            end. /*Additional Cost*/
                        
                        
         end. /*if v_file1 begins v_prefix*/

      end. /* REPEAT:input from value (m_inpath + v_infile1). */

  input close.
  /*
  end. /* REPEAT of INPUT STREAM data-stream FROM OS-DIR(m_inpath) NO-ECHO.*/ 
  */
  /** calculate tax and invoice amount variance */
  if can-find (first tt_CInvoiceAdditional) then 
  do:
   for each tt_tCInvoiceCIAPM break by tt_tCInvoiceCIAPM.tc_Rowid.
       for each tt_tAPMatchingCIAPM where tt_tAPMatchingCIAPM.tc_ParentRowid = tt_tCInvoiceCIAPM.tc_Rowid.
               find prh_hist where prh_domain    = global_domain
               /*
                               and prh_nbr       = tt_tAPMatchingCIAPM.tcPurchaseOrderNumber
                               */
                               and prh_line      = tt_tAPMatchingCIAPM.tiPurchaseOrderLineNumber 
                               and prh_receiver  = tt_tAPMatchingCIAPM.tcReceiverNumber 
                                                           no-lock no-error.
                   if available prh_hist then do: 
                  

                   find tx2d_det no-lock  where tx2d_nbr = prh_nbr
                                            and tx2d_line = prh_line
                                            and tx2d_domain = prh_domain
                                            and tx2d_ref = prh_receiver
                                            no-error.
                   if available tx2d_det then 
                   do:
                   
                   /*
                   find tx2_mstr where tx2_mstr.tx2_domain = Global_domain
                                    and tx2_mstr.tx2_tax_type = v_taxType
                                    and tx2_mstr.tx2_pt_taxc  = prh_taxc
                                    and tx2_mstr.tx2_tax_usage = prh_tax_usage
                                    and tx2_mstr.tx2_effdate   <= prh_rcp_date
                                    and (tx2_mstr.tx2_exp_date  = ? or 
                                         tx2_mstr.tx2_exp_date >= prh_rcp_date)
                                     no-lock no-error.
                                     */
                        find tx2_mstr where tx2_domain = prh_domain
                                        and tx2_tax_code = tx2d_tax_code
                                          no-lock no-error.              
                                     
                                     
                  if avail tx2_mstr then 
                  do:                  
                   find tt_CInvoiceAdditional where tt_CInvoiceAdditional.tt_invoicenumber = tt_tCInvoiceCIAPM.tc_Rowid no-error.
                  assign tt_CInvoiceAdditional.tt_qadtaxamt =  tt_CInvoiceAdditional.tt_qadtaxamt +                              
                  round(round(tt_tAPMatchingCIAPM.tdMatchQty  *  tt_tAPMatchingCIAPM.tdMatchUnitPrice,2) * tx2_tax_pct / 100 , 2)
                          tt_CInvoiceAdditional.tt_qadinvamt =  tt_CInvoiceAdditional.tt_qadinvamt + 
                                   round(tt_tAPMatchingCIAPM.tdMatchQty  *  tt_tAPMatchingCIAPM.tdMatchUnitPrice,2).
                                   
                  end. /*  if avail tx2_mstr then  */       
                   else 
                   do:
                      find tt_CInvoiceAdditional where tt_CInvoiceAdditional.tt_invoicenumber = tt_tCInvoiceCIAPM.tc_Rowid no-error.
                        assign 
                          tt_CInvoiceAdditional.tt_qadinvamt =  tt_CInvoiceAdditional.tt_qadinvamt + 
                                   round(tt_tAPMatchingCIAPM.tdMatchQty  *  tt_tAPMatchingCIAPM.tdMatchUnitPrice,2).
                   end. /*  not avail tx2_mstr then  */
                   end. /*  if available tx2d_det then  */ 

                   else do:
                      find tt_CInvoiceAdditional where tt_CInvoiceAdditional.tt_invoicenumber = tt_tCInvoiceCIAPM.tc_Rowid no-error.
                        assign 
                          tt_CInvoiceAdditional.tt_qadinvamt =  tt_CInvoiceAdditional.tt_qadinvamt + 
                                   round(tt_tAPMatchingCIAPM.tdMatchQty  *  tt_tAPMatchingCIAPM.tdMatchUnitPrice,2).
                   
                   end.

                   
                   end. /* if available prh_hist */
                   
                  
                   else 
                   do:
                   v_cnt = v_cnt + 1.
                  create api_status.
                  assign api_status.data_seq         = v_cnt
                         api_status.traceid          = v_infile1
                         api_status.dataid           = "PRH_HIST"
                         api_status.return_status    = "ERROR"  
                         api_status.message_type     = "Pre-validation"
                         api_status.message_string   = "PRH_HIST NOT EXIST" + "_" + 
                                                         tt_tAPMatchingCIAPM.tcPurchaseOrderNumber  + "_" +
                                                         tt_tAPMatchingCIAPM.tcReceiverNumber  + "_" +
                                                         string(tt_tAPMatchingCIAPM.tiPurchaseOrderLineNumber).
                                                               
                   end.

       end. /* for each tt_tAPMatchingCIAPM where  */
           
           if tt_tCInvoiceCIAPM.tc_Status = "N" then do:
       find tt_CInvoiceAdditional where tt_CInvoiceAdditional.tt_invoicenumber = tt_tCInvoiceCIAPM.tc_Rowid  no-error.
           
           if  tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt  <> 0 then do:

      
                  
                  find first domains where domains.domaincode = global_domain no-lock no-error.
      
                  for each domainsharedset of domains no-lock .
                  find SharedSet of domainsharedset  no-lock no-error.
                  if sharedset.sharedsettypecode = "GL" then
                      do:
                        
                         find GL where GL.SharedSet_ID = SharedSet.SharedSet_ID 
                                   and GL.GLcode =  entry(4,l_fdata)
                                   and GL.GLTypeCode = "VAT" no-lock no-error.
                     
                   end. /* if sharedset.sharedsettypecode = "GL" then */  
                 end. /*   for each domainsharedset of domains no-lock . */     
               if available GL then 
               do:                                                                          
                      create tt_tAPMatchingCostCIAPM.
                      assign
                         tt_tAPMatchingCostCIAPM.tcGLCode             = tt_CInvoiceAdditional.tt_taxacc
                         tt_tAPMatchingCostCIAPM.tcTaxEnvironment     = v_taxEnv
                         tt_tAPMatchingCostCIAPM.tcTaxUsage           = v_taxUsage
                         tt_tAPMatchingCostCIAPM.tcTaxClass           = v_taxClass
                         tt_tAPMatchingCostCIAPM.ttTaxPointDate       = today
                         tt_tAPMatchingCostCIAPM.tcTaxTransactionType = "55"
                         tt_tAPMatchingCostCIAPM.tcTransactionType    = "Purchase"
                         tt_tAPMatchingCostCIAPM.tc_Rowid             = string(fiGetNextRowID())
                         tt_tAPMatchingCostCIAPM.tc_ParentRowid       = tt_CInvoiceAdditional.tt_invoicenumber
                         tt_tAPMatchingCostCIAPM.tc_Status            = "N"
                         tt_tAPMatchingCostCIAPM.tcPostingVatInOut    = "Input"
                         tt_tAPMatchingCostCIAPM.tcFromTaxZone        = v_tzFrom
                         tt_tAPMatchingCostCIAPM.tcToTaxZone          = v_tzTo
                         tt_tAPMatchingCostCIAPM.tcTaxType            = v_taxType
                         tt_tAPMatchingCostCIAPM.tcPostingVatCode     = v_taxCode
                         tt_tAPMatchingCostCIAPM.tcPostingVatDomain   = global_domain
                         tt_tAPMatchingCostCIAPM.tcCurrencyCode       = tt_CInvoiceAdditional.tt_currency
                      .                                                               
                      assign
                         tt_tAPMatchingCostCIAPM.tdVatDebitTC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt
                         tt_tAPMatchingCostCIAPM.tdVatDebitLC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt
                         tt_tAPMatchingCostCIAPM.tdVatDebitCC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt.
                         
                         v_basedebit = (tAPMatchingCostCIAPM.tdVatDebitLC * 100) / tAPMatchingCostCIAPM.tdVatDebitLC no-error.
                         v_basedebit = round(v_basedebit,2).
                         
                         assign
                            tt_tAPMatchingCostCIAPM.tdBaseDebitTC = v_basedebit
                            tt_tAPMatchingCostCIAPM.tdBaseDebitLC = v_basedebit
                            tt_tAPMatchingCostCIAPM.tdBaseDebitCC = v_basedebit.           
               end. /*  if available GL then do */
               else do:
                  create tt_tAPMatchingCostCIAPM.
                  assign
                     tt_tAPMatchingCostCIAPM.tcGLCode = tt_CInvoiceAdditional.tt_taxacc
                     tt_tAPMatchingCostCIAPM.tcDivisionCode    = ""
                     tt_tAPMatchingCostCIAPM.tcCostCentreCode  = ""
                     tt_tAPMatchingCostCIAPM.tcProjectCode     = ""
                     tt_tAPMatchingCostCIAPM.tcTaxEnvironment = v_taxEnv
                     tt_tAPMatchingCostCIAPM.tcTaxUsage = v_taxUsage
                     tt_tAPMatchingCostCIAPM.tcTaxClass = v_taxClass
                     tt_tAPMatchingCostCIAPM.tc_Rowid      = string(fiGetNextRowID())
                     tt_tAPMatchingCostCIAPM.tc_ParentRowid = tt_CInvoiceAdditional.tt_invoicenumber
                     tt_tAPMatchingCostCIAPM.tc_Status      = "N"
                  .                                                              
                 assign
                     tt_tAPMatchingCostCIAPM.tdDebitTC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt
                     tt_tAPMatchingCostCIAPM.tdDebitLC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt
                     tt_tAPMatchingCostCIAPM.tdDebitCC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt. 

               end. /* Not vat account */
           
           
        
           
            
           
           end. /* if  tt_CInvoiceAdditional.tt_qadtaxamt - tt_CInvoiceAdditional.tt_tottaxamt <> 0 then do: */
           
            
           if  tt_CInvoiceAdditional.tt_totinvamt - tt_CInvoiceAdditional.tt_qadinvamt <> 0 then do:
                      create tt_tAPMatchingCostCIAPM.
                      assign
                         tt_tAPMatchingCostCIAPM.tcGLCode = tt_CInvoiceAdditional.tt_glacc
                         tt_tAPMatchingCostCIAPM.tcDivisionCode    = tt_CInvoiceAdditional.tt_division
                         tt_tAPMatchingCostCIAPM.tcCostCentreCode  = tt_CInvoiceAdditional.tt_costcenter
                         tt_tAPMatchingCostCIAPM.tcProjectCode     = ""
                         tt_tAPMatchingCostCIAPM.tcTaxEnvironment = v_taxEnv
                         tt_tAPMatchingCostCIAPM.tcTaxUsage = v_taxUsage
                         tt_tAPMatchingCostCIAPM.tcTaxClass = v_taxClass
                         tt_tAPMatchingCostCIAPM.tc_Rowid      = string(fiGetNextRowID())
                         tt_tAPMatchingCostCIAPM.tc_ParentRowid = tt_CInvoiceAdditional.tt_invoicenumber
                         tt_tAPMatchingCostCIAPM.tc_Status      = "N"
                      .                                                              
                     assign
                         tt_tAPMatchingCostCIAPM.tdDebitTC  =  tt_CInvoiceAdditional.tt_totinvamt - tt_CInvoiceAdditional.tt_qadinvamt
                         tt_tAPMatchingCostCIAPM.tdDebitLC  =  tt_CInvoiceAdditional.tt_totinvamt - tt_CInvoiceAdditional.tt_qadinvamt
                         tt_tAPMatchingCostCIAPM.tdDebitCC  =  tt_CInvoiceAdditional.tt_totinvamt - tt_CInvoiceAdditional.tt_qadinvamt.           
           
           end. /* tt_CInvoiceAdditional.tt_qadinvamt - tt_CInvoiceAdditional.tt_totinvamt <> 0 then do: */
          if  tt_CInvoiceAdditional.tt_allcamt <> 0 then do:
                      create tt_tAPMatchingCostCIAPM.
                      assign
                         tt_tAPMatchingCostCIAPM.tcGLCode = tt_CInvoiceAdditional.tt_glacc
                         tt_tAPMatchingCostCIAPM.tcDivisionCode    = tt_CInvoiceAdditional.tt_division
                         tt_tAPMatchingCostCIAPM.tcCostCentreCode  = tt_CInvoiceAdditional.tt_costcenter
                         tt_tAPMatchingCostCIAPM.tcProjectCode     = ""
                         tt_tAPMatchingCostCIAPM.tcTaxEnvironment = v_taxEnv
                         tt_tAPMatchingCostCIAPM.tcTaxUsage = v_taxUsage
                         tt_tAPMatchingCostCIAPM.tcTaxClass = v_taxClass
                         tt_tAPMatchingCostCIAPM.tc_Rowid      = string(fiGetNextRowID())
                         tt_tAPMatchingCostCIAPM.tc_ParentRowid = tt_CInvoiceAdditional.tt_invoicenumber
                         tt_tAPMatchingCostCIAPM.tc_Status      = "N"
                      .                                                              
                     assign
                         tt_tAPMatchingCostCIAPM.tdDebitTC  =  tt_CInvoiceAdditional.tt_allcamt 
                         tt_tAPMatchingCostCIAPM.tdDebitLC  =  tt_CInvoiceAdditional.tt_allcamt 
                         tt_tAPMatchingCostCIAPM.tdDebitCC  =  tt_CInvoiceAdditional.tt_allcamt .           
           
           end. /* tt_CInvoiceAdditional.tt_qadinvamt - tt_CInvoiceAdditional.tt_totinvamt <> 0 then do: */
           
           end. /* if = "N" */
   end. /* for each tt_tCInvoiceCIAPM break by tt_tCInvoiceCIAPM.tc_Rowid. */

 
  /** Validate Entity code **/
  /** Supplier code/PO number/Currency/sub account
       cost centre/ payment reference/ ap period  **/
    assign  v_error = no.     
        
     /** Validate Company Code */
         for each tt_tCInvoiceCIAPM exclusive-lock:

         for first Domains no-lock
        where DomainCode = global_domain,
     first Company of Domains no-lock
        where CompanyCode = tt_tCInvoiceCIAPM.tcCompanyCode:
     end.
     
     if not available Company
     then do:
        /*Not a valid company*/
        {us/bbi/pxmsg.i &msgnum = 28 &ERRORLEVEL = 1 &msgbuffer = m_tmpstr}
        v_cnt = v_cnt + 1.
        create api_status.
        assign api_status.data_seq         = v_cnt
               api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
               api_status.dataid           = "Company Code"
               api_status.return_status    = "ERROR"  
               api_status.message_type     = "Pre-validation"
               api_status.message_string   =  m_tmpstr.
     end. /*IF NOT AVAILABLE Company THEN*/
     
      /* Supplier Code */
     for first Creditor
        where CreditorCode = tt_tCInvoiceCIAPM.tcCreditorCode
     no-lock:
     end.
     
     if not available Creditor
     then do:
        /* Supplier code does not exist*/
        {us/bbi/pxmsg.i &MSGNUM = 8601 &ERRORLEVEL = 1 &MSGBUFFER = m_tmpstr }
        v_cnt = v_cnt + 1.
        create api_status.
        assign api_status.data_seq         = v_cnt
               api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
               api_status.dataid           = "supplier Code"
               api_status.return_status    = "ERROR"  
               api_status.message_type     = "Pre-validation"
               api_status.message_string   =  m_tmpstr.
     end.
     
     /* to be continue */
    
     /* Posting date validation */
     for last Period of company
        where  PeriodStatus      = "PERIODOPEN"
        and PeriodStartDate     <= date(tt_tCInvoiceCIAPM.ttCInvoicePostingDate)
        and PeriodEndDate       >= date(tt_tCInvoiceCIAPM.ttCInvoicePostingDate)
        and PeriodIsPostingPurchAllow no-lock: /*157231 Added N0-LOCK*/
     end.
     
     if not available period
     then do:
        /*25057 Period closed*/
        {us/bbi/pxmsg.i &MSGNUM=25057 &ERRORLEVEL=1 &msgbuffer=m_tmpstr}
        ASSIGN
           
        v_cnt = v_cnt + 1.
        create api_status.
        assign api_status.data_seq         = v_cnt
               api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
               api_status.dataid           = "Entity Period"
               api_status.return_status    = "ERROR"  
               api_status.message_type     = "Pre-validation"
               api_status.message_string   =  m_tmpstr.
     end.

   //   for first tt_CInvoiceAdditional where tt_CInvoiceAdditional.tt_invoicenumber
   //                                                   = tt_tCInvoiceCIAPM.tcCInvoiceReference no-lock.
   //   if  tt_CInvoiceAdditional.tt_oaseq = "" then 
   //   do:
   //   v_cnt = v_cnt + 1.
   //   create api_status.
   //   assign api_status.data_seq         = v_cnt
   //          api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
   //          api_status.dataid           = "Entity Period"
   //          api_status.return_status    = "ERROR"  
   //          api_status.message_type     = "Pre-validation"
   //          api_status.message_string   =  m_tmpstr.    
   //     end.                                     
   //    end. /* check invoice nbr  */ 
      
 
        
     /* TSMReference */
     for first code_mstr
        where code_mstr.code_domain  = global_domain
        and   code_mstr.code_fldname = "XX_PAYREFSEPA"
        and   code_mstr.code_value   = tt_tCInvoiceCIAPM.tcCInvoiceTSMNumber
     no-lock:
        v_desc = code_cmmt.
     end.
     if not available code_mstr
     then do:
        m_arg1 = "GCM not defined for input tcCInvoiceTSMNumber".
        /*GCM not defined for #*/
        {us/bbi/pxmsg.i &MSGNUM = 9203 &ERRORLEVEL = 1 &MSGBUFFER=m_tmpstr &msgarg1=m_arg1}
        //   v_cnt = v_cnt + 1.
   //   create api_status.
   //   assign api_status.data_seq         = v_cnt
   //          api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
   //          api_status.dataid           = "Entity Period"
   //          api_status.return_status    = "ERROR"  
   //          api_status.message_type     = "Pre-validation"
   //          api_status.message_string   =  m_tmpstr.    
     end.
           
     for each tt_tAPMatchingCIAPM no-lock
        where tt_tAPMatchingCIAPM.tc_ParentRowid = tt_tCInvoiceCIAPM.tc_Rowid:
        
        
        /* Purchase Order */
        for first po_mstr 
           where po_domain   = global_domain
           and   po_nbr      = tt_tAPMatchingCIAPM.tcPurchaseOrderNumber
        no-lock:
        end.
        
        if not available po_mstr
        then do:
           /* NOT A VALID PURCHASE ORDER */
           {us/bbi/pxmsg.i &MSGNUM=343 &ERRORLEVEL=1 &msgbuffer=m_tmpstr}
                v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
            api_status.dataid           = "PURCHASE ORDER"
            api_status.return_status    = "ERROR"  
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  m_tmpstr.    
           
        end.
        else if po_vend <> tt_tCInvoiceCIAPM.tcCreditorCode
        then do:
           /*6280 Supplier specified does not match supplier on the PO*/
           {us/bbi/pxmsg.i &MSGNUM=6280 &ERRORLEVEL=1 &msgbuffer=m_tmpstr}
           v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
            api_status.dataid           = "not match supplier"
            api_status.return_status    = "ERROR"  
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  m_tmpstr. 
        end.
        
    end. /* for each tt_tAPMatchingCIAPM no-lock */
     
     /** assign input file name into temp-table **/
     assign tt_tCInvoiceCIAPM.tcCInvoiceReferenceInt = v_infile1.
     
  end. /*EACH tCInvoiceCIAPM Data*/
  /** above all validation is finished **/
  
 /** if validation passed and need to import invoice **/
      if not can-find(first api_status) and v_import
          then do:
               
         cimloop:
         do transaction on error  undo cimloop , leave cimloop:
            
                

               for each tt_tCInvoiceCIAPM exclusive-lock
                  where tt_tCInvoiceCIAPM.tc_Status = "N" 
                  break by tt_tCInvoiceCIAPM.tt_seq_number:
                  /*
                  tt_tCInvoiceCIAPM.tcCInvoiceReference:
                  */
                  empty temp-table tFcMessages.
                  empty temp-table tAPMatchingCIAPM.
                  empty temp-table tCInvoiceCIAPM.
                  empty temp-table tAPMatchingCostCIAPM.
                                   
                  create tCInvoiceCIAPM.
                  buffer-copy tt_tCInvoiceCIAPM to tCInvoiceCIAPM.
                 
                     for each tt_tAPMatchingCIAPM no-lock where 
                                            tt_tAPMatchingCIAPM.tc_ParentRowid = tCInvoiceCIAPM.tc_Rowid
                        break by tt_tAPMatchingCIAPM.tc_ParentRowid:
                        /* check whether need to assign this value */
                        tCInvoiceCIAPM.tcReceiverNumber        = tt_tAPMatchingCIAPM.tcReceiverNumber.
                        create tAPMatchingCIAPM.
                        buffer-copy tt_tAPMatchingCIAPM to tAPMatchingCIAPM.
                     end.
                                         
                                         for each tt_tAPMatchingCostCIAPM no-lock where 
                                            tt_tAPMatchingCostCIAPM.tc_ParentRowid = tCInvoiceCIAPM.tc_Rowid
                        break by tt_tAPMatchingCostCIAPM.tc_ParentRowid:
                       
                        create tAPMatchingCostCIAPM.
                        buffer-copy tt_tAPMatchingCostCIAPM to tAPMatchingCostCIAPM.
                     end.
                        
                    
                  
              
                  run proxy/bcinvoiceapmatching.p persistent set vhProxyComponent.
         
                  run ApiMaintainByDatasetWithOutput in vhProxyComponent
                  (input  tt_tCInvoiceCIAPM.tcCompanyCode,
                     input  "save",
                     input  true,
                     input  true,
                     input  icPartialUpdateExceptionList,
                     input  dataset BCInvoiceAPMatching by-reference,
                     output ocPrimaryKey,
                     output ocRowid,
                     output oiDraftInstance,
                     output ocPrimaryKeyName,
                     output dataset-handle vho,
                     output dataset tFcMessages,
                     output oiReturnStatus).
                   
                  assign
                     errflag = no
                     errflpt = m_outpath + m_errfile.

                  for each tFcMessages :

                    if tFCMessages.tcFcType = "W" then next.  

                     if index(tFcMessages.tcFcMessage,"warning") <> 0 or
                     index(tFcMessages.tcFcMessage, "The sum of the base and tax amounts") <> 0 then
                     next.
                     
                     if index(tFcMessages.tcFcMsgNumber, "qadfin-500498") <> 0 then
                     next.

                     if index(tFcMessages.tcFcMsgNumber, "QadFin-8125") <> 0 then
                     next.
                     
                     v_cnt = v_cnt + 1.
                     if v_cnt > 200 then leave.
                     
                     assign
                        errflag  = yes.
                       
                     
                     if tFcMessages.tcFcFieldName <> "" then
                     do:
                        
                        create api_status.
                        assign api_status.data_seq         = v_cnt
                               api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
                               api_status.dataid           = "Load Error"
                               api_status.return_status    = "ERROR"  
                               api_status.message_type     = "Pre-validation"
                               api_status.message_string   = gettermlabel("SEVERITY",8) + " = " +
                               string(tFcMessages.tiFcSeverity) + " | " +
                               tFcMessages.tcFcMessage + " | " +
                               gettermlabel("FIELD_NAME",10) + " = " +
                               tFcMessages.tcFcFieldName + " | " +
                               gettermlabel("FIELD_LABEL",11) + " = " +
                               tFcMessages.tcFcFieldLabel + " | " +
                               gettermlabel("FIELD_VALUE",11) + " = " +
                               tFcMessages.tcFcFieldValue + " | " +
                               tFcMessages.tcFcMsgNumber.

                     end.
                     else 
                     do:
                        create api_status.
                        assign api_status.data_seq         = v_cnt
                               api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
                               api_status.dataid           =  "Load Error"
                               api_status.return_status    = "ERROR"  
                               api_status.message_type     = "Pre-validation"
                               api_status.message_string   = gettermlabel("SEVERITY",8) + " = " +
                               string(tFcMessages.tiFcSeverity) + " | " +
                               tFcMessages.tcFcMessage + " | " +
                               tFcMessages.tcFcMsgNumber.
                     end.
                    
                     
                  end. /* for each tFcMessages : */
             
                  delete procedure vhProxyComponent.
                  if not errflag then 
                                  tt_tCInvoiceCIAPM.tcCInvoiceRemark = "Success".
                                  else 
                                  tt_tCInvoiceCIAPM.tcCInvoiceRemark = "Failed".
                  if errflag
                  then do:
                     /*2677 Unable to load mapped document data from file #*/
                     {us/bbi/pxmsg.i 
                        &msgnum=2677 
                        &ERRORLEVEL=1 
                        &msgbuffer=m_tmpstr
                        &msgarg1 = tt_tCInvoiceCIAPM.tcCInvoiceReferenceInt}
                        v_cnt = v_cnt + 1.
                        create api_status.
                        assign api_status.data_seq         = v_cnt
                               api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
                               api_status.dataid           =  "Load Error"
                               api_status.return_status    = "ERROR"  
                               api_status.message_type     = "Pre-validation"
                               api_status.message_string   = m_tmpstr.
                     
                  end.
                  else do:
                                  
                     for first tt_CInvoiceAdditional where tt_CInvoiceAdditional.tt_invoicenumber
                                                     = tt_tCInvoiceCIAPM.tcCInvoiceReference no-lock.
                     end. /* for first tt_CInvoiceAdditional   */     
                                         
                     for first Cinvoice
                        where CInvoice_ID = int64(ocPrimaryKey)
                     exclusive-lock:
                                         
                         cinvoice.cinvoicedescription = tt_CInvoiceAdditional.tt_rmk.
                      find first journal no-lock where journal.journal_id = cinvoice.journal_id  no-error.

                    v_cnt = v_cnt + 1.
                    create api_status.
                    assign api_status.data_seq         = v_cnt
                           api_status.traceid          = v_infile1
                           api_status.dataid           = tt_tCInvoiceCIAPM.tcCInvoiceReference
                           api_status.return_status    = "Successfully"  
                           api_status.message_type     = "Loading"
                           api_status.message_string   =  string(Cinvoice.CInvoicePostingYear,"9999") + "/" +
                                                           journal.journalcode + "/" +
                                                           string(Cinvoice.CInvoiceVoucher,"999999999").
                   
     
                
                        Cinvoice.Customshort1           = tt_CInvoiceAdditional.tt_oaseq.
                
                     end. /*for first Cinvoice*/
                                         
                      for first cinvoiceposting where cinvoiceposting.cinvoice_id =
                                  int64(ocPrimaryKey):
                      find first posting where posting.posting_id = cinvoiceposting.posting_id no-error.
                      if avail posting then
                            postingtext = Cinvoice.cinvoicedescription.
                      end.                    
                   
                     /*11948 File was successfully loaded*/
                     {us/bbi/pxmsg.i 
                        &msgnum=11948 
                        &ERRORLEVEL=1 
                        &msgbuffer=m_tmpstr
                        &msgarg1 = tt_tCInvoiceCIAPM.tcCInvoiceReferenceInt}

                        v_cnt = v_cnt + 1.
                        create api_status.
                        assign api_status.data_seq         = v_cnt
                               api_status.traceid          = tt_tCInvoiceCIAPM.tcCInvoiceReference
                               api_status.dataid           =  ""
                               api_status.return_status    = "Successfully"  
                               api_status.message_type     = "After Loaded"
                               api_status.message_string   = m_tmpstr.
                     
                  end.
               end. /*for each tt_tCInvoiceCIAPM exclusive-lock*/
         end. /* CIMLOOP*/
      
         if v_infile1 <> "" then 
         unix silent value("mv " + m_inpath + v_infile1 + " " + m_archpath).

        
      end.  /*IF not v_error AND v_import then  do :*/
  
   
 
   
   end. /* if can-find tt_CInvoiceAdditional */
   
   else 
   do:
    /*4479 No files to process*/
      {us/bbi/pxmsg.i &msgnum = 4479 &ERRORLEVEL = 1 &msgbuffer = m_tmpstr}
        v_cnt = v_cnt + 1.
        create api_status.
        assign api_status.data_seq         = v_cnt
               api_status.traceid          = v_infile1
               api_status.dataid           = ""
               api_status.return_status    = "ERROR"  
               api_status.message_type     = "Pre-validation"
               api_status.message_string   =  m_tmpstr.

   end.        


   vc_outputjson = m_inpath + replace(v_infile1,".csv",".json").
    run writejsonfile(input hresult,
                  input vc_outputjson,
                  input "FILE",
                  input True,
                  input "UTF-8",
                  output vl_RetOK,
                  output vc_errorstring).   
                  
                  
  {us/gp/gpselout.i &printType = "printer"
   &printWidth = 132
   &pagedFlag = " "
   &stream = " "
   &appendToFile = " "
   &streamedOutputToTerminal = " "
   &withBatchOption = "yes"
   &displayStatementType = 1
   &withCancelMessage = "yes"
   &pageBottomMargin = 6
   &withEmail = "yes"
   &withWinprint = "yes"
   &defineVariables = "yes"}
   
 

 
  for each api_status.
     
     export api_status.
  
  end.
  
  put unformatted m_inpath + v_infile1 skip.
  /*
  for each tt_tAPMatchingCIAPM .
  export tt_tAPMatchingCIAPM.
  end.
   
 */

   {us/mf/mfrtrail.i}


end. /* repeat */



procedure getTaxDet:
   
   define input  parameter v_input1      as character.
   define input  parameter v_input2      as character.
   define input  parameter v_taxUsage    as character.
   define input  parameter v_tax_class   as character.
   define input  parameter v_pointdate   as date.
   define input  parameter v_taxable     as logical.
   define output parameter v_taxEnv      as character.
   define output parameter v_taxType     as character.
   define output parameter v_taxRate     as decimal.
   define output parameter v_vatCode     as character.
   define output parameter v_taxAccount  as character.
   define output parameter m_from        as character.
   define output parameter m_to          as character.
   define output parameter v_taxCode     as character.
   define output parameter v_taxCNaccount     as character.
   
   define variable m_from1        as character.
   
   def buffer bf_ad_mstr for ad_mstr.
   
   assign
      v_taxEnv    = ""
      v_taxType   = ""
      v_taxRate   = 0
      v_vatCode   = ""
      v_taxAccount= ""
      m_from1 = ""
      v_taxCNaccount = ""
      .
  
   for first creditor no-lock
      where creditorcode = v_input1,
      first businessrelation of creditor,
      first address of businessrelation:
      m_from = address.TxzTaxZone.
   end.
   
   for first company no-lock
      where companycode = v_input2 ,
      first companyproperty of company,
      first businessrelation of companyproperty,
      first address of businessrelation:
      m_to = address.TxzTaxZone.
   end.
   

   
   m_from1 = m_from.
   
   if v_tax_class  <> "" then
   do:
      substring(m_from1,17) = v_tax_class.
   end.
   
   
  
   for first txe_mstr no-lock
      where txe_zone_from = m_from1
      and txe_zone_to   = m_to:
   end.
   if available txe_mstr then
   do:
      v_taxEnv = txe_desc.
      
      for first txed_det no-lock
         where txed_tax_env = txe_desc:
      end.
      if available txed_det then
      do:
         for first vd_mstr no-lock
            where vd_domain = global_domain
            and vd_addr   = v_input1:
         end.
         if available vd_mstr and v_taxable then
         do:
            for last tx2_mstr no-lock
               where tx2_domain    = global_domain
               and tx2_tax_type  = txed_tax_type
               and tx2_pt_taxc   = v_tax_class
               and tx2_tax_usage = v_taxUsage
               and ((tx2_effdate <= v_pointdate and tx2_exp_date = ?)
               or (tx2_effdate <= v_pointdate  and tx2_exp_date >= v_pointdate)):
              
            end.
           
            if available tx2_mstr then
            do:
               assign
                  v_taxType     = tx2_tax_type
                  v_taxRate     = tx2_tax_pct
                  v_taxAccount  = tx2_ap_acct
                  v_taxCNaccount = tx2_ap_cn_acct
                  v_taxCode     = tx2_tax_code
                  .
            end.
         end.
         else
         do:
            for last tx2_mstr no-lock
               where tx2_domain    = global_domain
               and tx2_tax_type  = v_noTax
               and tx2_effdate   < today:
            end.
            if available tx2_mstr then
            do:
           
               assign
                  v_taxType     = tx2_tax_type
                  v_taxRate     = tx2_tax_pct
                  v_taxAccount  = tx2_ap_acct
                  v_taxCNaccount = tx2_ap_cn_acct
                  v_taxCode     = tx2_tax_code
                  .
            end.
         end.
      end.
   end.
   
   for first creditor no-lock
      where creditorcode = v_input1,
      first txu_mstr where creditor.txutaxusage = txu_tax_usage,
      first domains  where domaincode = GLOBAL_DOMAIN,      
      first vat where vat.domain_id   = domains.domain_id   
      and vat.txutaxusage = txu_tax_usage:
      v_vatCode = vatcode.
   end.
   if v_vatCode = "" then
   v_vatCode = v_taxCode.
   
end.





